package com.gurun.model.base;

import com.gurun.model.bean.ApiResult;
import com.gurun.model.gson_adapter.ApiException;

import java.util.concurrent.CancellationException;

import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;

public abstract class ResultObserver<T> implements SingleObserver<T> {

    @Override
    public void onSubscribe(Disposable d) {
        onLoading(d);
    }

    @Override
    public final void onSuccess(T result) {
        onLoaded();
        try {
            ApiResult apiResult = (ApiResult) result;
            if (apiResult != null && "0".equals(apiResult.getRetCode())) {
                onSuccess(result, apiResult.getRetMsg());
            } else {
                onApiError(apiResult);
            }
        } catch (Exception e) {
            onOtherError(e);
        }
    }

    @Override
    public final void onError(Throwable e) {
        onLoaded();

        if (e instanceof ApiException) {
            //noinspection unchecked
            onApiError(((ApiException) e).getApiResult());
        } else if (e instanceof CancellationException) {
            onDisposed(e);
        } else {
            onOtherError(e);
        }
    }

    public abstract void onLoading(Disposable d);

    public abstract void onLoaded();

    public abstract void onSuccess(T result, String msg);

    public abstract void onApiError(ApiResult result);

    public abstract void onOtherError(Throwable e);

    public void onDisposed(Throwable e) {

    }
}
